package com.gxa.modules.app.hospitalization.rechargeAndExpenses.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.gxa.common.utils.UUIDUtils;
import com.gxa.modules.app.hospitalization.rechargeAndExpenses.mapper.InpatientDetailAppMapper;
import com.gxa.modules.app.hospitalization.rechargeAndExpenses.mapper.RechargeOrderDetailAppMapper;
import com.gxa.modules.app.hospitalization.rechargeAndExpenses.service.InpatientDetailAppService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.modules.app.outpatient.onlinepay.dto.PayDetail;
import com.gxa.modules.app.outpatient.onlinepay.mapper.OnlinePayMapper;
import com.gxa.modules.model.dto.*;
import com.gxa.modules.model.entity.fee.InpatientDetail;

import com.gxa.modules.model.entity.fee.InpatientRechargeRecords;
import com.gxa.modules.model.entity.fee.RechargeOrderDetail;
import com.gxa.modules.model.vo.InpatientDetailVo;
import com.gxa.modules.pc.fee.mapper.InpatientRechargeRecordsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 住院信息表 服务实现类
 * </p>
 *
 * @author lst
 * @since 2022-11-13
 */
@Service
@Slf4j
public class InpatientDetailAppServiceImpl extends ServiceImpl<InpatientDetailAppMapper, InpatientDetail> implements InpatientDetailAppService {

    //调用住院信息
    @Autowired
    private InpatientDetailAppMapper inpatientDetailAppMapper;

    //调用住院充值订单信息
    @Autowired
    private RechargeOrderDetailAppMapper rechargeOrderDetailAppMapper;
    //住院充值记录
    @Autowired
    private InpatientRechargeRecordsMapper inpatientRechargeRecordsMapper;
    //别人的
    @Autowired
    private OnlinePayMapper onlinePayMapper;

    /*
    按患者的id和登陆用户id查询住院信息和就诊信息
     */
    @Override
    public InpatientDetailDto queryById(Integer patientId, Integer useId) {

        return inpatientDetailAppMapper.queryById(patientId, useId);
    }

    /*
    根据患者id和时间段查询充值订单信息表
     */
    @Override
    public List<PayDetail> queryByTime(Date startTime, Date endTime, Integer id) {
        return rechargeOrderDetailAppMapper.queryByTime(startTime, endTime, id);
    }

    /*
    根据登陆用户的id查询所有的住院人信息
     */
    @Override
    public List<InpatientDto> listAll(Integer userId) {
        return inpatientDetailAppMapper.listAll(userId);
    }

    /*
    根据患者的id查询就诊卡的金额
     */
    @Override
    public CardDto queryByPatientIdToCard(Integer id) {
        return inpatientDetailAppMapper.queryByPatientIdToCard(id);
    }

    /*
    按时间查询住院记录
     */
    @Override
    public List<HospitalizationDto> queryByTimeToHospitalization(Date startTime, Date endTime, Integer id) {
        return rechargeOrderDetailAppMapper.queryByTimeToHospitalization(startTime, endTime, id);
    }

    /*
    根据住院缴费记录id查询对应患者的身份证信息
    1、查询出住院时间和出院时间
    2、计算出住院时长
     */
    @Override
    public IdCardDto queryByIdToMsg(Integer id) {
        IdCardDto idCardDto = rechargeOrderDetailAppMapper.queryByIdToHospitalization(id);
        Date date1 = idCardDto.getInHospitalTime();
        Date date2 = idCardDto.getLeaveHospitalTime();

        log.info("-InHospitalTime---{}----LeaveHospitalTime-{}---", date1,date2);

        long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);
        idCardDto.setTime(betweenDay);

        return idCardDto;
    }

    /**
     *原来是根据患者Id和消费记录单的Id查询这次住院记录总的药费
     *
     * 后面改成返回住院记录所有的数据
     * @param patientId
     * @param id
     * @return
     */
    @Override
    public FreeAndDateDto queryByTimeToMoney(Integer patientId, Integer id) {
        //根据患者Id和消费记录单的Id查询这次住院记录总的药费
        FreeAndDateDto dto = rechargeOrderDetailAppMapper.queryByTimeToMoney(patientId, id);
        Date startDate = dto.getStartDate();
        Date endDate = dto.getEndDate();

        log.info("--startDate{}}------endDate{}-", startDate, endDate);
        List<cn.hutool.core.date.DateTime> list = new ArrayList<>();
        List<cn.hutool.core.date.DateTime> dateList = DateUtil.rangeToList(startDate, endDate, DateField.DAY_OF_YEAR);//创建日期范围生成器
        for (DateTime dt : dateList) {
            list.add(dt);
        }

        dto.setDates(list);

        return dto;
    }

    //新增住院人
    @Override
    public String add(Integer id) {

        //通过患者id先去查询一次住院信息id
        Integer integer = inpatientDetailAppMapper.queryByPatientIdToInpatientNum(id);

        //进行判断
        if (integer == null){
            //随机生成一个六位数
            String s = RandomUtil.randomNumbers(6);
            //获取当前系统时间
            DateTime date = DateUtil.date();

            InpatientDetailVo vo = new InpatientDetailVo(id, s, date);

            inpatientDetailAppMapper.add(vo);
            return "添加成功";
        }else {
            return "该用户已有住院卡";
        }

    }

    /**
     * 充值并生成充值订单
     */
    @Override
    @Transactional
    public String pay(double money,Integer id,Integer userId,String pwd) {

//        //充值的金额
//        Double money = (Double) params.get("rechargeMoney");
//        //当前的患者id
//        Integer id = (Integer) params.get("id");
//        //当前患者输入的pwd
//        String pwd = (String) params.get("pwd");
//        //当前登陆用户id
//        Integer userId = (Integer) params.get("userId");
        //真正的支付密码
        String paypassword = onlinePayMapper.getByUserId(userId);
        //获取患者的余额
        Double balance = inpatientRechargeRecordsMapper.balanceFromPatient(id);

        //住院信息id
        Integer inpatientNum = inpatientDetailAppMapper.queryByPatientIdToInpatientNum(id);
        //获取当前系统时间
//        Date date = DateUtil.date();
        LocalDateTime date = LocalDateTime.now();

        if (pwd.equals(paypassword)){
            try {
                //随机生成一个订单号
                String orderNum = "GXA" + UUIDUtils.createOnlyId();

                //生成住院充值订单信息表
                RechargeOrderDetail r = new RechargeOrderDetail();
                r.setOrderTotal(money).setPatientId(id).setOrderNum(orderNum).setBalance(balance).setCreateTime(date);
                rechargeOrderDetailAppMapper.insert(r);
                //获取生成的订单id
                Integer id1 = r.getId();

                //生成住院充值记录表
                InpatientRechargeRecords i = new InpatientRechargeRecords();
                i.setPatientId(id).setRechargeOrderId(id1).setCreateTime(date).setInInfoId(inpatientNum);
                inpatientRechargeRecordsMapper.insert(i);

                //更改就诊人就诊卡的余额
                double totalMoney = money + balance;
                onlinePayMapper.updateMoney(totalMoney,id);

            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException();
            }
            return "充值成功";

        }else {
            return "支付密码错误";
        }
    }

}
